package git.soulbgm.security.handler;

import git.soulbgm.common.constant.HttpStatus;
import git.soulbgm.common.pojo.ResultData;
import git.soulbgm.common.pojo.ReturnCode;
import git.soulbgm.utils.JsonUtil;
import git.soulbgm.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理类
 *
 * @author SoulBGM
 * @date 2020-08-03
 */
@Slf4j
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String ip = RequestUtil.getRemoteIpByServletRequest(request, true);
        log.info("登录失败,登录IP: {}", ip);
        String msg = "登录失败";
        if (e instanceof SessionAuthenticationException) {
            msg = "当前已登录了一个用户";
        } else if (e instanceof InternalAuthenticationServiceException) {
            msg = e.getMessage();
        }
        ResultData resultData = ResultData.getResultData(HttpStatus.UNAUTHORIZED, msg);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JsonUtil.toJson(resultData));
    }
}
